package cn.schoolwow.util.test.module.replaceFile.ruoyi.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.resource.QueryResource;
import cn.schoolwow.util.domain.query.resource.QueryResourceResponse;
import cn.schoolwow.util.module.query.resource.domain.SingleQueryResourceHandler;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ModifyRuoYiDirectoryNameFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String directoryPath = flowContext.checkData("directoryPath", String.class);
        String projectName = flowContext.checkData("projectName", String.class);

        Path basePath = Paths.get(directoryPath);
        flowContext.putTemporaryData("basePath", basePath);

        QueryResource.newQuery("项目目录", directoryPath)
                .fileNameStartWith("ruoyi-")
                .singleQueryResourceHandler(new SingleQueryResourceHandler() {
                    @Override
                    public boolean handleQueryResourceResponse(QueryResourceResponse queryResourceResponse) {
                        File file = queryResourceResponse.getAsFile();
                        String fileName = file.getName();
                        String newFileName = projectName+"-"+fileName.substring("ruoyi-".length());
                        File newFile = new File(file.getParent()+"/"+newFileName);
                        file.renameTo(newFile);
                        String sourcePath = basePath.relativize(file.toPath()).toString();
                        String targetPath = basePath.relativize(newFile.toPath()).toString();
                        System.out.println("重命名文件["+sourcePath+"]为["+targetPath+"]");
                        return true;
                    }
                })
                .execute()
                .walkResource();
    }

    @Override
    public String name() {
        return "修改若依文件夹名称";
    }
}
